//
//  AlarmHomeVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/4/22.
//
// 【首页-报警通知】报警记录-网点

import Foundation
import UIKit

class AlarmHomeVC: SubLevelViewController, PullToRefreshPresentable {
    // 布防撤防通知
    let topV = AlarmHomeTopView()
    
    var alarmV: AlarmStatisticsAlarmView!
    var datas : [AlarmsModal?] = []

    var pageNum: Int = 1
    var totalPage: Int64 = 0
    
    var listParam = AlarmCommonParam(pageNum: 1, pageSize: PageSize, dateType: "1")

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "报警记录"
        view.backgroundColor = .bg
        NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NotiAlarm, object: nil)
        
        setupNavItems()

        if deptName == nil {
            deptName = BSUser.currentUser.deptName
            deptId = BSUser.currentUser.deptId
        }
        
        listParam.tbCompanyId = "\(deptId ?? -1)"
        
        alarmV = AlarmStatisticsAlarmView(deptId: deptId, deptName: deptName)

        setupPullToRefresh(on: alarmV.aTable.tableView)

        setupUI()
        
        reloadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navBarStyle(.white)
    }
    
    deinit {
        alarmV.aTable.tableView.removeAllPullToRefresh()
    }
    
    func reloadAction() {
        pageNum = 1
        getList()
    }
    
    func loadAction() {
        if pageNum >= totalPage {
            return
        }
        pageNum += 1
        getList()
    }
        
    @objc func searchTapped() {
        let bSearchVC = BranchSearchVC()
        bSearchVC.didSelectBranchWith = { (dept, _) -> () in
            self.deptName = dept.deptName
            self.deptId = dept.deptId
            self.reloadData()
            bSearchVC.navigationController?.popViewController(animated: true)
        }
        navigationController?.pushViewController(bSearchVC, animated: true)
    }
    
    @objc func chartTapped() {
        navigationController?.pushViewController(AlarmReportVC(withDeptId: deptId, deptName: deptName), animated: true)
    }
    
    @objc func msgTapped() {
        navigationController?.pushViewController(AlarmReplyVC(), animated: true)
    }
    
    @objc func reloadData() {
        /// 网点撤布防信息
        let param = AlarmCommonParam(dateType: listParam.dateType, tbCompanyId: "\(deptId ?? -1)")
        API.getAlarmCbfByTbCompanyId(withParam: param) { responseModel in
            DispatchQueue.main.async {
                let models = responseModel.models ?? []
                self.topV.updateUI(withModal: models)
                if models.count > 0 {
                    self.topV.snp.remakeConstraints { (make) in
                        make.left.equalToSuperview().offset(10)
                        make.right.equalToSuperview().offset(-10)
                        make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(10)
                        make.height.equalTo(models.count * 90)
                    }
                } else {
                    self.topV.snp.remakeConstraints { (make) in
                        make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
                        make.height.equalTo(0)
                    }
                }
            }
        }
        
        // 报警类型统计
        API.getAlarmCountByType(withParam: AlarmCommonParam(tbCompanyId: "\(deptId ?? -1)")) { responseModel in
            DispatchQueue.main.async {
                let models = responseModel.models?.filter({$0?.dictValue != "5" && $0?.dictValue != "6"})
                self.alarmV.header.cardsV.updateUI(withModels: models ?? [])
            }
        }
        
        // 列表
        pageNum = 1
        getList()
    }
    
    func getList() {
        listParam.pageNum = pageNum
        
        view.showToastActivity()
        /// 报警记录
        API.getAlarmList(withParam: listParam) { responseModel in
            if self.pageNum > 1 && (responseModel.models == nil || responseModel.models?.count == 0) {
                self.pageNum -= 1
                return
            }
            if self.pageNum == 1 {
                self.datas.removeAll()
            }
            self.totalPage = responseModel.totalPage
            self.datas.append(contentsOf: responseModel.models ?? [])
            DispatchQueue.main.async {
                self.view.hideToastActivity()
                self.alarmV.aTable.datas = self.datas
            }
        }
    }
    
    func setupUI() {
        view.addSubview(topV)
        topV.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.height.equalTo(0)
        }
        
        alarmV.aTable.needReload = { () -> () in
            self.reloadData()
        }
        alarmV.header.filterV.dateCtl.didSelectItemWith = { (index, modal) -> () in
            self.alarmV.header.filterV.dateCtl.key = modal.name
            self.listParam.dateType = modal.id
            self.reloadData()
        }
        alarmV.header.filterV.statusCtl.didSelectItemWith = { (index, modal) -> () in
            if modal.id == nil {
                self.alarmV.header.filterV.statusCtl.key = "处置状态"
            } else {
                self.alarmV.header.filterV.statusCtl.key = modal.name
            }
            self.listParam.status = modal.id
            self.reloadData()
        }
        
        view.addSubview(alarmV)
        alarmV.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(topV.snp.bottom)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
    
    func setupNavItems() {
        let chartBtn = UIButton(type: .custom)
        chartBtn.setImage(UIImage(named: "ic_chart"), for: .normal)
        chartBtn.addTarget(self, action: #selector(chartTapped), for: .touchUpInside)
        chartBtn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        chartBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
        let chartBar = UIBarButtonItem(customView: chartBtn)
        
//        let searchBtn = UIButton(type: .custom)
//        searchBtn.setImage(UIImage(named: "ic_search"), for: .normal)
//        searchBtn.addTarget(self, action: #selector(searchTapped), for: .touchUpInside)
//        searchBtn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
//        searchBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
//        let searchBar = UIBarButtonItem(customView: searchBtn)
//
//        let msgBtn = UIButton(type: .custom)
//        msgBtn.setImage(UIImage(named: "ic_alarm_msg"), for: .normal)
//        msgBtn.addTarget(self, action: #selector(msgTapped), for: .touchUpInside)
//        msgBtn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
//        msgBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
//        let msgBar = UIBarButtonItem(customView: msgBtn)
//
//        navigationItem.rightBarButtonItems = [msgBar, chartBar]
        navigationItem.rightBarButtonItems = [chartBar]
    }
}
